package com.it.cloud.modules.websocket.controller;

import cn.hutool.json.JSONUtil;
import com.it.cloud.common.base.Result;
import com.it.cloud.modules.rabbitmq.producer.MqService;
import com.it.cloud.modules.websocket.WebSocketServer;
import com.it.cloud.modules.websocket.dto.SocketMessageDTO;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;

/**
 * wbsocket 推送
 *
 * @author 司马缸砸缸了
 * @date 2019/7/29 13:44
 * @description
 */

@RestController
@RequestMapping("/socket")
public class SocketController {

    @Autowired
    private MqService mqService;

    //页面请求
    @GetMapping("/{userId}")
    public ModelAndView socket(@PathVariable String userId) {
        ModelAndView mav=new ModelAndView("/websocket");
        mav.addObject("userId", userId);
        return mav;
    }
    //推送数据接口
    @ResponseBody
    @RequestMapping("/push/{userId}")
    public Result pushToWeb(@PathVariable String userId, String message) {
        SocketMessageDTO dto = new SocketMessageDTO();
        dto.setUserId(userId);
        dto.setMessage(message);

        // 发送到所有队列
        mqService.fanout(JSONUtil.toJsonStr(dto));
        /*try {
            WebSocketServer.sendInfo(message,userId);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(userId+"#"+e.getMessage());
        }*/
        return Result.ok(userId);
    }
}
